package com.itheima.comfyui.client.config;

import com.itheima.comfyui.client.api.ComfyuiApi;
import com.itheima.comfyui.client.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Configuration
public class ComfyuiConfig {
    @Bean
    public ComfyuiApi comfyuiApi() {
        //创建拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        //拦截日志级别为BODY
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //创建ok客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //添加拦截器
                .addInterceptor(loggingInterceptor)
                //是否在连接失败时自动重试一次
                .retryOnConnectionFailure(true)
                //链接超时时间为30 秒
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                //请求地址
                .baseUrl("http://127.0.0.1:8188")
                //序列化
                .addConverterFactory(JacksonConverterFactory.create())
                //重新设定Retrofit底层使用的OkHttp客户端 打印日志
                .client(okHttpClient)
                .build();
        ComfyuiApi comfyuiApi = retrofit.create(ComfyuiApi.class);
        return comfyuiApi;
    }

    @Bean
    public ComfyuiMessageHandler comfyuiMessageHandler() {
        //注入消息处理类
        return new ComfyuiMessageHandler();
    }
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager()  {
        WebSocketClient webSocketClient = new StandardWebSocketClient();
        String url = "ws://127.0.0.1:8188/ws?clientId=abc1234";
        //链接客户端,消息处理器,请求url
        WebSocketConnectionManager wsc = new WebSocketConnectionManager(webSocketClient,comfyuiMessageHandler(),url);
        //启动
        wsc.start();
        return wsc;
    }

}
